package org.shj.tdpl.loader.loader.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.shj.tdpl.common.constant.TdplConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * When running many test case in the same time, some test cases maybe use the same tables. So the 
 * test data may be deleted even if the test case doesn't finished.
 * This class should be thread safe.
 * 
 * @author huangjian
 */
@Slf4j
public class MultiFileDataLoader extends AbstractXlsxDataLoader{

	@Override
	protected void loadData(List<String> tables, int... versions) throws Exception{
		List<String> insert = new ArrayList<>();
		List<String> delete = new ArrayList<>();
		List<String> updateAfterInsert = new ArrayList<>();
		List<String> updateBeforeDel = new ArrayList<>();
		
		InputStream ins = null;
		try{
			for(String tbl : tables){
				ins = new FileInputStream(generatedFilePath + File.separator + tbl + ".xlsx");
				XSSFWorkbook book = new XSSFWorkbook(ins);
				XSSFSheet sheet = book.getSheet(tbl);
				
				FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
				getSqlsNeedToBeExecute(sheet, evaluator, insert, delete, updateAfterInsert, updateBeforeDel, versions);

				ins.close();
			}
			
			executeSqls(insert, delete, updateAfterInsert, updateBeforeDel);
			
		}catch(Exception e){
			log.error("Error when reading excel.");
			throw e;
			
		}finally{
			if(ins != null){
				ins.close();
			}
		}
		
	}

	@Override
	protected XSSFWorkbook getCommonInfoBook() throws Exception{
		String filePath = generatedFilePath + File.separator + TdplConstants.Common_Info_File_Name + ".xlsx";
		try(InputStream ins = new FileInputStream(filePath)){
			return new XSSFWorkbook(ins);
		}catch(Exception e){
			log.error("Error when reading excel.");
			throw e;
		}
	}

}
